package com.hhxy.response;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 测试使用字节流响应数据
 */
@WebServlet("/ResponseDemo4")
public class ResponseDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、使用字节输入流读取文件
        InputStream is = new FileInputStream("D:\\Test\\1.gif");
        //2、获取response字节输出流对象
        ServletOutputStream sos = response.getOutputStream();
        //3、将输入流对象的数据拷贝给输出流对象

        /*方式一：使用字节流按字节数组复制文件*/
        /*byte[] buff1 = new byte[1024];
        int len = 0;
        while(((len = is.read(buff1)) != 1)){
            sos.write(buff1,0,len);
        }
        is.close();*/
        //is是自己创建的所以需要手动关，ServletOutputStream是response创建的，不用手动关，后面同理

        /*方式二：使用字节缓冲流按字节数组复制文件*/
        /*InputStream bis = new BufferedInputStream(is);
        byte[] buff2 = new byte[1024];
        int len = 0;
        while((len = bis.read(buff2)) != -1){
            sos.write(buff2,0,len);
        }
        bis.close();*/

        /*方式三：使用Java提供的API*/
        /*byte[] buff3 = is.readAllBytes();
        sos.write(buff3);*/

        /*方式四：使用commons-io工具包提供的方法*/
        IOUtils.copy(is,sos);
    }
}
